//
//  SMWindowPopupManager.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/9.
//

import SwiftUI

// 弹窗项结构
struct PopupItem {
    let id = UUID()
    let view: AnyView
    var dismissAction: (() -> Void)?
}

// 弹窗管理器 - 支持 dismiss 回调
class SMWindowPopupManager {
    static let shared = SMWindowPopupManager()
    
    private var popupWindow: UIWindow?
    private var hostingController: UIHostingController<AnyView>?
    private var popupItems: [PopupItem] = []
    
    func showPopup<Content: View>(
        isPresented: Binding<Bool>,
        config: SMPopupConfig,
        onDismissCompleted: (() -> Void)? = nil, // 新增：dismiss 完成回调
        @ViewBuilder content: @escaping () -> Content
    ) {
        DispatchQueue.main.async {
            print("显示弹窗，当前弹窗数量: \(self.popupItems.count)")
            
            guard let scene = UIApplication.shared.connectedScenes
                .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene else {
                return
            }
            
            // 如果窗口不存在，创建新窗口
            if self.popupWindow == nil {
                print("创建新弹窗窗口")
                let popupWindow = UIWindow(windowScene: scene)
                popupWindow.frame = UIScreen.main.bounds
                popupWindow.windowLevel = .alert + 1
                popupWindow.backgroundColor = .clear
                
                let hostingController = UIHostingController(rootView: AnyView(EmptyView()))
                hostingController.view.backgroundColor = .clear
                
                popupWindow.rootViewController = hostingController
                popupWindow.makeKeyAndVisible()
                
                self.popupWindow = popupWindow
                self.hostingController = hostingController
            }
            
            // 创建弹窗视图
            let popupView = SMPopupWindowContainer(
                config: config,
                content: content,
                onDismiss: { [weak self] in
                    print("弹窗执行 onDismiss")
                    self?.removeLastPopup()
                    isPresented.wrappedValue = false
                    // 调用 dismiss 完成回调
                    onDismissCompleted?()
                },
                onDismissHandlerAvailable: { [weak self] dismissHandler in
                    self?.addDismissAction(dismissHandler)
                }
            )
            
            // 添加到弹窗数组
            let popupItem = PopupItem(view: AnyView(popupView))
            self.popupItems.append(popupItem)
            
            // 更新窗口内容
            self.updateWindowContent()
        }
    }
    
    func dismissPopup(for isPresented: Binding<Bool>, onCompleted: (() -> Void)? = nil) {
        DispatchQueue.main.async {
            print("手动关闭弹窗")
            if let lastItem = self.popupItems.last {
                // 如果有回调，需要特殊处理
                if let onCompleted = onCompleted {
                    // 临时保存回调，在 dismiss 完成后调用
                    self.tempDismissCallback = onCompleted
                }
                lastItem.dismissAction?()
            }
            isPresented.wrappedValue = false
        }
    }
    
    // 临时保存 dismiss 回调
    private var tempDismissCallback: (() -> Void)?
    
    private func addDismissAction(_ dismissHandler: @escaping () -> Void) {
        if let index = popupItems.indices.last {
            // 包装 dismissHandler，在动画完成后调用临时回调
            let wrappedDismissHandler: () -> Void = {
                dismissHandler()
                // 执行临时回调（如果有）
                self.tempDismissCallback?()
                self.tempDismissCallback = nil
            }
            popupItems[index].dismissAction = wrappedDismissHandler
        }
    }
    
    private func removeLastPopup() {
        print("移除最后一个弹窗")
        if !popupItems.isEmpty {
            popupItems.removeLast()
        }
        
        if popupItems.isEmpty {
            cleanupWindow()
        } else {
            updateWindowContent()
        }
    }
    
    private func updateWindowContent() {
        guard let hostingController = hostingController else { return }
        
        if popupItems.isEmpty {
            print("没有弹窗，隐藏窗口")
            hostingController.rootView = AnyView(EmptyView())
            popupWindow?.isHidden = true
        } else {
            print("更新窗口内容，弹窗数量: \(popupItems.count)")
            let stackView = ZStack {
                ForEach(Array(popupItems.enumerated()), id: \.element.id) { index, item in
                    item.view
                        .zIndex(Double(index))
                }
            }
            
            hostingController.rootView = AnyView(stackView)
            popupWindow?.isHidden = false
            popupWindow?.makeKeyAndVisible()
        }
    }
    
    private func cleanupWindow() {
        print("清理弹窗窗口")
        self.popupWindow?.isHidden = true
        self.popupWindow?.rootViewController = nil
        self.popupWindow = nil
        self.hostingController = nil
        self.popupItems.removeAll()
    }
    
    func getPopupCount() -> Int {
        return popupItems.count
    }
    
    func clearAllPopups() {
        print("清空所有弹窗")
        for item in popupItems.reversed() {
            item.dismissAction?()
        }
        popupItems.removeAll()
        cleanupWindow()
    }
}

